package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listTree() {
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(new QueryWrapper<>());
        // 共三级级联菜单
        // TODO 1、首先查找所有一级菜单，也就是parent_cid=0的数据
        List<CategoryEntity> levelMenu1 = categoryEntityList.stream()
                .filter(c -> c.getParentCid() == 0)
                .map(menu -> {
                    menu.setChildren(getChildCategory(menu, categoryEntityList));
                    return menu;
                })
                .sorted((menu1, menu2) -> {
                    // 顺序
                    return (ObjectUtils.isNotEmpty(menu1.getSort()) ? menu1.getSort() : 0) - (ObjectUtils.isNotEmpty(menu2.getSort()) ? menu2.getSort() : 0);
                })
                .collect(Collectors.toList());

        return levelMenu1;
    }

    /**
     * 查找子菜单
     *
     * @param currentCategory 当前菜单
     * @param all             所以菜单
     * @return
     */
    public List<CategoryEntity> getChildCategory(CategoryEntity currentCategory, List<CategoryEntity> all) {
        // TODO 2、查找二级菜单，也就是parent_cid = 一级菜单的cat_id
        List<CategoryEntity> childMenuList = all.stream()
                .filter(item -> item.getParentCid() == currentCategory.getCatId())
                .map(menu -> {
                    // TODO 3、查找三级菜单，也就是parent_cid = 二级菜单的cat_id
                    menu.setChildren(getChildCategory(menu, all));
                    return menu;
                })
                .sorted((menu1, menu2) -> {
                    // 顺序
                    return (ObjectUtils.isNotEmpty(menu1.getSort()) ? menu1.getSort() : 0) - (ObjectUtils.isNotEmpty(menu2.getSort()) ? menu2.getSort() : 0);
                })
                .collect(Collectors.toList());
        return childMenuList;
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO  1、检查当前删除的菜单，是否被别的地方引用
        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catId) {
        List<Long> paths = new ArrayList<>();
        // 递归方法获取对应的父菜单
        List<Long> parentPath = this.findParentPath(catId, paths);
        Collections.reverse(parentPath);
        logger.info(String.valueOf(parentPath));
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 获取对应的父菜单 225,34,2
     * @param catId
     * @param paths
     * @return
     */
    private List<Long> findParentPath(Long catId, List<Long> paths){
        paths.add(catId);
        // 获取当前菜单
        CategoryEntity categoryEntity = this.getById(catId);
        // 获取对应的父菜单id
        Long parentCid = categoryEntity.getParentCid();
        if (0L != parentCid){
            this.findParentPath(categoryEntity.getParentCid(), paths);
        }
        return paths;
    }

}